package com.chaos.system.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chaos.framework.model.dto.ID;
import com.chaos.framework.model.dto.page.PageList;
import com.chaos.framework.model.dto.page.PageQueryDto;
import com.chaos.framework.model.entity.Table;
import com.chaos.framework.model.helper.ConvertHelper;
import com.chaos.framework.model.helper.PageHelper;
import com.chaos.system.api.dto.TTenantIndexDto;
import com.chaos.system.entity.TTenant;
import com.chaos.system.api.data.TTenantData;
import com.chaos.system.mapper.TTenantMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Jacky.Cui
 * @since 2024-12-02
 */
@Slf4j
@Component
public class TTenantService extends ServiceImpl<TTenantMapper, TTenant> {

    public ID insertModel(TTenantData data) {
        TTenant entity = ConvertHelper.convert(data, TTenant.class);
        return save(entity) ? new ID(entity.getId()) : null;
    }

    public boolean deleteModel(ID data) {
        return removeById(data.getId());
    }

    public boolean updateModelByID(TTenantData data) {
        TTenant entity = ConvertHelper.convert(data, TTenant.class);
        return update(entity, new UpdateWrapper<TTenant>().eq(Table.ID, data.getId()));
    }

    public TTenantData selectByID(ID data) {
        return ConvertHelper.convert(getOne(new QueryWrapper<TTenant>().eq(Table.ID, data.getId())), TTenantData.class);
    }

    public List<TTenantData> selectByData(TTenantData data) {
        LambdaQueryWrapper<TTenant> query = new LambdaQueryWrapper<>();
        query.eq(!ObjectUtil.isEmpty(data.getId()), TTenant::getId, data.getId());
        query.orderByDesc(TTenant::getId);
        return ConvertHelper.convert(list(query), TTenantData.class);
    }

    public PageList<TTenantData> selectByPage(PageQueryDto<TTenantData> pageData) {

        TTenantData data = pageData.getData();
        LambdaQueryWrapper<TTenant> query = new LambdaQueryWrapper<>();
        query.eq(!ObjectUtil.isEmpty(data.getId()), TTenant::getId, data.getId()).eq(!ObjectUtil.isEmpty(data.getStatus()), TTenant::getStatus, data.getStatus())
                .eq(!ObjectUtil.isEmpty(data.getPhone()), TTenant::getPhone, data.getPhone()).like(!ObjectUtil.isEmpty(data.getName()), TTenant::getName, data.getName());

        query.orderByAsc(TTenant::getId);

        return PageHelper.pageList(page(PageHelper.page(pageData), query), TTenantData.class);
    }

    public List<TTenantIndexDto> listIndex() {
        return baseMapper.listIndex();
    }
}
